package cn.green.business.entity;

import cn.green.utils.StringUtils;

import java.util.*;

/**
 * 树形结构的实体
 */
public abstract class TreeEntity<E extends TreeEntity> extends Entity{

    //直接父级id
    protected String parentId;

    //所有父级id
    protected String parentIds;
    //子节点
    protected List<E> children;

    public String getParentId() {
        return parentId;
    }

    public void setParentId(String parentId) {
        this.parentId = parentId;
    }

    public String getParentIds() {
        return parentIds;
    }

    public void setParentIds(String parentIds) {
        this.parentIds = parentIds;
    }

    public List<E> getChildren() {
        return children;
    }

    public void setChildren(List<E> children) {
        this.children = children;
    }

    /**
     * 重写toString方法
     * @return
     *//*
    public String toString() {
        return toJsonString();
    }

    *//**
     * 重写toJsonString方法
     * @return
     *//*
    public String toJsonString() {
        return null;
    }*/

    /**
     * 根据数据源制作树
     * @param src   数据源
     * @return
     */
    public E buildTree(List<E> src) {
        if (StringUtils.isEmpty(this.id)) {
            return null;
        }
        for (int i = 0; i < src.size(); i++) {
            E next = src.get(i);
            String parentId = next.getParentId();
            if (!StringUtils.isEmpty(parentId)) {
                if (this.id.equals(parentId)) {
                    E treeNode = (E) next.buildTree(src);
                    if (this.children == null) {
                        this.children = new ArrayList<E>();
                    }
                    src.remove(i--);
                    this.children.add(treeNode);
                }
            }
        }
        return (E) this;
    }

    /**
     * 把当前节点及当前节点的子节点放入至list集合中
     * @return
     */
    public List<E> buildList() {
        if (this == null) {
            return null;
        }
        List<E> rtn = new ArrayList<E>();
        this.addNode((E)this, rtn);
        return rtn;
    }

    private void addNode(E e, List<E> list) {
        list.add(e);
        List<E> children = e.getChildren();
        if (children != null) {
            for (int i = 0; i < children.size(); i++) {
                E item = children.get(i);
                children.remove(i--);
                this.addNode(item, list);
            }
        }
    }
}
